﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using MessagingToolkit.QRCode.Codec;

namespace QRCodeGenerator
{
    /// <summary>
    /// Interaction logic for QRGenerator.xaml
    /// </summary>
    public partial class QrGeneratorGadget
    {
        public QrGeneratorGadget()
        {
            InitializeComponent();
        }

        private void TexChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(textBox.Text)) return;
            var qrGenerator = new QRCodeEncoder
                                  {
                                      QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
                                      QRCodeScale = 4,
                                      QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M,
                                      QRCodeVersion=4
                                  };

            var image = qrGenerator.Encode((String)textBox.Text);


            if (CodeImage == null) return;
            CodeImage.Source = TransformBitmap(image);
            CodeImage.Height = CodeImage.Source.Height;
            this.Height = CodeImage.Height + textBox.Height + 30;
        }

        ImageSource TransformBitmap(Bitmap bmp)
        {
            var bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = ConvertImageToMemoryStream(bmp);
            bi.EndInit();
            return bi;
        }

        private static Stream ConvertImageToMemoryStream(Bitmap bmp)
        {
            var result = new MemoryStream();
            bmp.Save(result, ImageFormat.Bmp);
            return result;
        }

        
    }
}
